<template>
  <BasicModal v-bind="$attrs" @register="userRegister" :title="getTitle" width="800px" okText="保存并关闭" @ok="submitAudit">
    <BasicTable @register="registerTable" :loading="loading" :pagination="{ pageSize: 20 }" :rowSelection="{ type: 'checkbox' }"> </BasicTable>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { ref, reactive } from 'vue';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { targerMList, addTarget } from '../LabWscientificItem.api';
  import { columnsMTarget } from '../LabWscientificItem.data';
  import { BasicTable } from '/@/components/Table';

  const loading = ref(false);
  const getTitle = ref('实验指标');
  const props = defineProps({
    itemsId: { type: String },
  });
  const queryParam = reactive<any>({});

  const formData = reactive<Record<string, any>>({
    itemsId: '',
    itemsTargetList: [
      {
        fieldCode: '',
        fieldName: '',
        fieldType: '',
      },
    ],
  });

  function resetA() {
    formData.itemsId = '';
    formData.targetList = [];
  }
  const emit = defineEmits(['getAuditResult', 'reload']);

  const [userRegister, { setModalProps, closeModal }] = useModalInner(async () => {
    setModalProps({
      minHeight: 180,
    });
    resetA();
    loading.value = true;
    // formData.itemsId = data.itemsId;
    formData.itemsId = props.itemsId;
  });

  // 注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      api: targerMList,
      columns: columnsMTarget,
      canResize: false,
      useSearchForm: false,
      showIndexColumn: true,
      showTableSetting: false,
      showActionColumn: false,
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
  });

  const [registerTable, { getSelectRows, clearSelectedRowKeys, reload }] = tableContext;

  async function submitAudit() {
    const selectedRows = getSelectRows();
    if (selectedRows.length > 0) {
      formData.itemsTargetList = selectedRows;
      formData.itemsId = props.itemsId;
      let result = await addTarget(formData);
      if (result.code === 200) {
        clearSelectedRowKeys();
        reload();
        emit('reload');
      }
    }
    closeModal();
  }
</script>
